package com.lry.sso.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lry.sso.common.entity.response.ResultData;
import com.lry.sso.common.entity.response.Ret;
import com.lry.sso.common.util.StringHelper;
import com.lry.sso.gateway.bean.ResponseWrapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.micrometer.core.instrument.util.IOUtils;
import lombok.SneakyThrows;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @author 李瑞益
 * @date 2020-02-12 12:28
 */
@Component
public class ResponseFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(ResponseFilter.class);

    /**
     * 分4种
     * pre => 路由前
     * route => 路由逻辑，实际的转发逻辑可以在这里实现
     * post => 后端返回的response，可以在这做一些处理
     * error => 异常处理
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    /**
    执行顺序
     */
    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER ;
    }

    /**
     * 是否执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        InputStream rds = RequestContext.getCurrentContext().getResponseDataStream();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        String body = IOUtils.toString(rds);

        if (response.getStatus() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            JSONObject errorBoby = JSON.parseObject(body);
            ResultData errorBody = Ret.error(StringHelper.valueOf(HttpStatus.SC_OK), StringHelper.valueOf(errorBoby.get("message")));
            body = JSON.toJSONString(errorBody);
        }
        logger.info("响应消息：{}", body);
        RequestContext.getCurrentContext().setResponseBody(body);
        return null;
    }
}
